package com.eastedu.superise.handler.question;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Pair;
import com.eastedu.client.warehouse.SimilarResourceSearchClient;
import com.eastedu.client.warehouse.model.QuestionMoreDetailWithSimilarityDTO;
import com.eastedu.client.warehouse.model.SearchConditionRequest;
import com.eastedu.repository.question.po.QuestionBasicInfoPO;
import com.eastedu.superise.handler.AbstractHistoricalDataHandler;
import com.eastedu.util.QuestionUtil;
import com.eastedu.utils.JsonUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author 袁松明
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SimilarQuestionHistoricalDataHandler extends AbstractHistoricalDataHandler<QuestionBasicInfoPO> {

    private final SimilarResourceSearchClient similarResourceSearchClient;
    private final Map<Long, List<Object>> cacheMap = new ConcurrentHashMap<>(50);


    @Override
    protected String getSql() {
        return "SELECT " +
                "   question.* " +
                "FROM" +
                "   question_service.t_question_basic_info AS question " +
                "WHERE " +
                "   question.id IN (1002905210567557120) " +
                "ORDER BY question.id";
    }

    @Override
    public void callback(QuestionBasicInfoPO questionBasicInfoPo) throws SQLException {
        log.debug("试题ID：{}，题干信息：{}", questionBasicInfoPo.getId(), questionBasicInfoPo.getQuestion());
        String questionContentString = QuestionUtil.extractContent(questionBasicInfoPo.getQuestion());
        if (Objects.isNull(questionContentString)) {
            log.warn("解析试题题干失败，跳过知识点填充，试题ID：{}", questionBasicInfoPo.getId());
            cacheMap.put(questionBasicInfoPo.getId(), Collections.emptyList());
            return;
        }
        log.info("解析试题题干成功：{}", questionContentString);
        List<QuestionMoreDetailWithSimilarityDTO> questions = this.getSimilarQuestion(questionContentString,
                questionBasicInfoPo.getStudyPeriod(), questionBasicInfoPo.getSubject());
        if (CollectionUtils.isEmpty(questions)) {
            log.warn("匹配试题失败，无相似题，试题ID：{}", questionBasicInfoPo.getId());
            cacheMap.put(questionBasicInfoPo.getId(), Collections.emptyList());
            return;
        }
        List<Object> objects = questions.stream()
                .map(o -> Pair.of(o.getBaseInfo().getId(), o.getConfidence())).collect(Collectors.toList());
        cacheMap.put(questionBasicInfoPo.getId(), objects);
        log.info("匹配成功，试题ID：{}", questionBasicInfoPo.getId());
    }

    @Override
    public void afterCompletion() {
        this.cacheMap.forEach((k, v) -> log.info("原试题ID【{}】,相似题ID{}", k, JsonUtil.toJsonString(v)));
    }

    private List<QuestionMoreDetailWithSimilarityDTO> getSimilarQuestion(String questionContentString, String studyPeriod, String subject) {
        SearchConditionRequest request = new SearchConditionRequest();
        request.setSection(studyPeriod);
        request.setSubject(subject);
        request.setContent(questionContentString);
        Map<String, Object> match = similarResourceSearchClient.match(request);
        if (CollUtil.isEmpty(match)) {
            return Collections.emptyList();
        }
        Object similarity = match.get("similarity");
        return JsonUtil.parseList(JsonUtil.toJsonString(similarity), QuestionMoreDetailWithSimilarityDTO.class);
    }

}
